package com.xuecheng.framework.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.Optional;

public class FeignClientInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes != null) {
            //获取request对象
            HttpServletRequest request = attributes.getRequest();
            Optional<Enumeration<String>> optional = Optional.ofNullable(request.getHeaderNames());
            if (optional.isPresent()) {
                Enumeration<String> headerNames = optional.get();
                while(headerNames.hasMoreElements()) {
                    String headerName = headerNames.nextElement();
                    String headerValue = request.getHeader(headerName);
                    if ("authorization".equals(headerName)) {
                        requestTemplate.header(headerName, headerValue);
                    }
                }
            }
        }
    }
}
